package com.treeman.api.controller.user;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.treeman.api.controller.ApiExceptionResolverController;
import com.treeman.api.security.context.AccessTokenAuthenticationToken;
import com.treeman.user.localization.LocalizationManager;
import com.treeman.user.localization.UserLocalization;

@Controller
@RequestMapping(value = "/api")
@PreAuthorize("isAuthenticated()")
public class UserLocalizationController extends ApiExceptionResolverController {

	private static Logger log = Logger
			.getLogger(UserLocalizationController.class);

	@Secured("ROLE_USER")
	@RequestMapping(value = "/me/localization", method = RequestMethod.POST)
	public @ResponseBody
	void setLocalization(
			@RequestParam(value = "localization", required = true) String localizationJson,
			HttpServletResponse response) {

		log.debug("Updating user localization...");

		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		if (auth instanceof AccessTokenAuthenticationToken) {

			Gson gson = new Gson();
			UserLocalization localization = gson.fromJson(localizationJson,
					UserLocalization.class);
			String username = auth.getName();

			LocalizationManager.getInstance().changeUserLocalization(username,
					localization);
		} else {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
	}
}
